package com.qiyun.asyncarrange;

import java.util.concurrent.*;

//198
public class CompletableFutureTest03 {
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
            200,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(100000),
            Executors.defaultThreadFactory(),//默认线程工厂
            new ThreadPoolExecutor.AbortPolicy()//拒绝策略
            //如果不想抛弃还要执行。可以使用new ThreadPoolExecutor.CallerRunsPolicy()
    );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * handle方法 可对结果做最后的处理（可处理异常），可改变返回值。
         * public <U> CompletionStage handle(BiFunction<? super T, Throwable, ? extends U> fn)
         * public <U> CompletionStage handleAsync(BiFunction<? super T, Throwable, ? extends U> fn)
         * public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor)
         *
         * 和.whenComplete的区别
         * whenComplete只能感知异常，结果。不能对结果进行修改。
         * 但handle或者exceptionally可以对结果进行修改
         *
         */


        System.out.println("main--start---");


        /*
          线程方法完成后的处理 可以获取返回值的
         */
        CompletableFuture<Integer> future03 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 0;
            System.out.println("运行结果..." + i);
            return i;

        }, executor).handle((res,thr)->{
            if (res!=null){
                return res*2;
            }
            if (thr!=null){
                return 0;
            }
            return 0;
        });

        System.out.println("异步执行的结果为"+future03.get());
        System.out.println("main--end---");
    }

}
